--#SET TERMINATOR @
DROP TRIGGER OpiekunDelete@

CREATE TRIGGER OpiekunDelete 
  BEFORE DELETE ON Opiekunowie
  --LANGUAGE SQL
  REFERENCING OLD AS o
  FOR EACH ROW MODE DB2SQL
  BEGIN ATOMIC
  	IF (SELECT COUNT(*) AS count FROM UczniowieOpiekunowie 
			WHERE Opiekun_id = o.id) <= 1 THEN
		SIGNAL SQLSTATE '70000';
	END IF;
    DELETE FROM UczniowieOpiekunowie WHERE Opiekun_id = o.id AND (SELECT COUNT(*) AS count FROM UczniowieOpiekunowie 
			WHERE Opiekun_id = o.id) > 1;
			
    DELETE FROM UzytkownicySystemu WHERE Opiekunowie_id = o.id AND (SELECT COUNT(*) AS count FROM UczniowieOpiekunowie 
			WHERE Opiekun_id = o.id) > 1;
  END
  @

  --#SET TERMINATOR ;